package libra;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@RestController
public class TestController {
	public static final String serviceName = "springboot-byCoding";
	EventListener listener = new EventListener() {
		@Override
		public void onEvent(Event event) {
			try {
				System.out.println( new ObjectMapper().writeValueAsString(event) );
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
		}
	};
	
	/*
	 * 前提条件：需要@EnableNacosDiscovery开启Nacos服务发现
	 * 通过@NacosInjected从Spring容器中获取NamingService实例
	 */
	@NacosInjected
	private NamingService naming;
	
	@PostConstruct
	public void init() throws NacosException {
		// 注册当前应用
		naming.registerInstance(serviceName, "127.0.0.1", 8080);
		// 监听服务
		naming.subscribe(serviceName, listener);
	}
	
	// 获取服务实例
	@RequestMapping("getRegisterInstance")
	public Object getRegisterInstance(String serviceName, String group, String clusters, HttpServletRequest req, HttpServletResponse resp) throws NacosException {
		List<Instance> allInstances = 
			naming.getAllInstances( serviceName, checkGroup(group), checkClusters(clusters), true );
		return allInstances;
	}
	
	// 注销当前服务实例
	@RequestMapping("deRegisterInstance")
	public Object deRegisterInstance(HttpServletRequest req, HttpServletResponse resp) throws NacosException {
		naming.deregisterInstance( serviceName, "127.0.0.1", 8080 );
		return "DEL_OK";
	}
	
	
	private String checkGroup( String group ) {
		return ( group == null || group.equals("") ? "DEFAULT_GROUP" : group );
	}
	private List checkClusters( String clusters ) {
		return ( clusters == null || clusters.equals("") ? List.of() : List.of(clusters) );
	}
}
